import pymysql
def connect_and_operate_mysql():
    # 数据库连接配置
    config = {
        'host': '192.168.10.10',
        'port': 3307,
        'user': 'root',
        'password': '123456',
        'database': 'saas_back'
    }
    try:
        # 连接数据库
        connection = pymysql.connect(**config)
        with connection.cursor() as cursor:
            # 执行查询操作
            sql_query = "SELECT * FROM users"
            cursor.execute(sql_query)
            result = cursor.fetchall()
            print("查询结果：")
            for row in result:
                print(row)

            # 执行插入操作
            sql_insert = "INSERT INTO users (id,user_name) VALUES (6, '张三')"
            # values = ('value1', 'value2')
            cursor.execute(sql_insert)
            connection.commit()  # 提交事务
            print("插入数据成功！")
    except pymysql.MySQLError as e:
        print(f"数据库操作失败，错误信息：{e}")
    finally:
        # 关闭连接
        if connection:
            connection.close()
            print("数据库连接已关闭。")


# 调用函数进行数据库连接和操作
connect_and_operate_mysql()
